package com.qianniu.napi.admin.service.impl;

import akka.actor.ActorRef;
import akka.actor.Props;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.github.stuxuhai.jpinyin.PinyinFormat;
import com.github.stuxuhai.jpinyin.PinyinHelper;
import com.google.common.base.Strings;
import com.qianniu.napi.admin.entity.*;
import com.qianniu.napi.admin.entity.dal.ESResultDO;
import com.qianniu.napi.admin.entity.penum.FantimeType;
import com.qianniu.napi.admin.entity.penum.IotypeEnum;
import com.qianniu.napi.admin.entity.penum.JftypeEnum;
import com.qianniu.napi.admin.mapper.UserMapper;
import com.qianniu.napi.admin.service.*;
import com.qianniu.napi.admin.service.akka.AKRealTemplate;
import com.qianniu.napi.admin.service.akka.AkkaServer;
import com.qianniu.napi.admin.service.akka.SignActor;
import com.qianniu.napi.admin.service.akka.UserActor;
import com.qianniu.napi.common.config.Constants;
import com.qianniu.napi.common.util.*;
import org.redisson.api.RMap;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.regex.Matcher;

@Service
public class WeixinServiceImpl implements IWeixinService {

    private static Logger logger = LoggerFactory.getLogger(WeixinServiceImpl.class);

    @Resource
    private UserMapper userMapper;
    @Autowired
    private IRedisService redisService;
    @Autowired
    private IResourceService resourceService;
    @Autowired
    private IGoodsService goodsService;
    @Autowired
    private IConfigService configService;
    @Autowired
    private IStoreService storeService;
    @Autowired
    private IUserService userService;
    @Autowired
    private IJifenService jifenService;

//    @Autowired
//    private SigninMapper signinMapper;

    /**
     * 处理微信发来的请求
     *
     * @param request
     * @return
     */
    public String processRequest(HttpServletRequest request, String mpid) {
        String respMessage = "";

        try {
            // 默认返回的文本消息内容
            String respContent = null;

            // xml请求解析
            // 调用消息工具类MessageUtil解析微信发来的xml格式的消息，解析的结果放在HashMap里；
            Map<String, String> requestMap = MessageUtil.parseXml(request);
            logger.debug(">>>>>> requestMap toString:" + JSON.toJSONString(requestMap));

            // 从HashMap中取出消息中的字段；
            // 发送方帐号（open_id）
            String openid = requestMap.get("FromUserName");
            // 公众帐号
            String toUserName = requestMap.get("ToUserName");
            String createTime = requestMap.get("CreateTime");
            // 消息类型
            String msgType = requestMap.get("MsgType");

            // 消息内容
            String content = requestMap.get("Content");
            // MsgId
            String msgId = requestMap.get("MsgId");

            //图片
            String PicUrl = requestMap.get("PicUrl");

            //小程序
            String AppId = requestMap.get("AppId");
            String PagePath = requestMap.get("PagePath");
            String ThumbUrl = requestMap.get("ThumbUrl");
            String ThumbMediaId = requestMap.get("ThumbMediaId");
            String Title = requestMap.get("Title");

            //进入会话事件
            String Event = requestMap.get("Event");
            String SessionFrom = requestMap.get("SessionFrom");

            // 记录日志
            Map map = new HashMap<String, String>();
            // token
//            String token = WeixinUtil.getAccessToken(mpid);
            // 文本消息
            if (msgType.equals(MessageUtil.REQ_MESSAGE_TYPE_TEXT)) {

                return processText(openid, toUserName, content, mpid);
            } else if (msgType.equals(MessageUtil.REQ_MESSAGE_TYPE_EVENT)) {

                // 事件推送
                String eventType = requestMap.get("Event");// 事件类型
                String eventKey = Strings.isNullOrEmpty(requestMap.get("EventKey")) ? "" : requestMap.get("EventKey");// 事件KEY值，与创建自定义菜单时指定的KEY值对应
                String qrscene[] = eventKey.replace("qrscene_", "").split("__");// 事件类型
                String parentOpenId = qrscene.length > 0 ? qrscene[0] : "";// 事件类型
                String sceneExtra = qrscene.length > 1 ? qrscene[1] : "";

                AkkaServer.system.actorOf(Props.create(SignActor.class)).tell(openid + "@" + requestMap.get("Latitude") + "@"
                        + requestMap.get("Longitude") + "@" + requestMap.get("Precision")
                        + "@" + eventType
                        + "@" + eventKey, ActorRef.noSender());

                String checkUserNullKey = Constants.USER_NULL_CHECK + openid + "_" + DateUtil.getToday();
                if (!Constants.checkMap.containsKey(checkUserNullKey))
                    Constants.checkMap.put(checkUserNullKey, new AtomicInteger(0));

                if (!eventType.equals(MessageUtil.EVENT_TYPE_UNSUBSCRIBE)
                        && Constants.checkMap.get(checkUserNullKey).compareAndSet(0, 1)) {

                    if (redisService.isnull(checkUserNullKey)) {
                        WeixinUtil.saveOrUpdateUser(openid, mpid, parentOpenId, 0, qrscene);
                        redisService.set(checkUserNullKey, "1", 1, TimeUnit.DAYS);
                    }
                }

                if (eventType.equals(MessageUtil.EVENT_TYPE_SUBSCRIBE)) {// 订阅

                    respContent = "你好，欢迎关注仟牛互动!";
                    String ticket = requestMap.get("Ticket");// 事件类型

                    AkkaServer.system.actorOf(Props.create(AKRealTemplate.class))
                            .tell(Constants.WX_CHECK_USER + "@" + openid + "@" + mpid + "@true", ActorRef.noSender());
//                    return MessageResponse.getTextMessage(openid, toUserName, respContent);

                    if (parentOpenId.equals("huiguo") || sceneExtra.equals("huiguo")) {

                        respContent += "\n感谢大驾对此公号的关注" +
                                "\n特推出如下0元特价包邮商品相送" +
                                "\n回复具体编号领取";
//                        String mediaId = redisService.get("huiguo_weixin_qr");
                        String txt = redisService.get("huiguo_reply");
                        WeixinUtil.sendCustomMsg(openid, respContent, Constants.WEIXIN_QIANBAIDU);
                        WeixinUtil.sendCustomMsg(openid, txt, mpid);
                        return "";
//                      WeixinUtil.sendCustomMsg(openid, Constants.WEIXIN_MATERIAL_IMAGE,txt,Constants.WEIXIN_QIANBAIDU);
                    }

                } else if (eventType.equals(MessageUtil.EVENT_TYPE_UNSUBSCRIBE)) {// 取消订阅
                    // TODO 取消订阅后用户再收不到公众号发送的消息，因此不需要回复消息
                    map.clear();
                    map.put("openid", openid);
                    map.put("isFocus", 0);
                    // 更新图片#待完善20190101
//                    userMapper.updateUser(map);

                    redisService.del(checkUserNullKey);
                    Constants.checkMap.remove(checkUserNullKey);

                } else if (eventType.equals(MessageUtil.EVENT_TYPE_SCAN)) {// 扫描

//                    Map<String,Object> map = new HashMap<String,Object>();
//                    map.put("openid",fromUserName);
//                    map.put("isFocus",0);
//                    userMapper.updateUser(map);

                } else if (eventType.equals(MessageUtil.EVENT_TYPE_CLICK)) {// 自定义菜单点击事件

                    logger.info("eventKey is:" + eventKey);
                    if (eventKey.equals("ribao")) {
                        String ribao = getClickResponse(eventKey, openid, mpid);
//                        Article article = new Article();
//                        article.setTitle("仟仟快报");
//                        article.setDescription(ribao);
//                        List<Article> list = new ArrayList<Article>();
//                        list.add(article);
//                        return MessageResponse.getNewsMessage(openid, toUserName, list);
                        return MessageResponse.getTextMessage(openid, toUserName, ribao);
                    } else if (eventKey.equals("video")) {

//                        return MessageResponse.getVedioMessage(openid, toUserName,mediaService.randomMedia());
                        String vkey = "video_" + openid + DateUtil.getToday();
                        List<String> rList = redisService.getList("video_mid");
                        String val = redisService.get(vkey);
                        int cout = Strings.isNullOrEmpty(val) ? 0 : Integer.valueOf(val);
                        cout++;

                        if (cout < rList.size()) {
                            WeixinUtil.sendCustomMsg(openid, Constants.WEIXIN_MATERIAL_VIDEO, rList.get(rList.size() - cout), mpid);
                        } else {
                            String txt = "本公众号每日更新一集精选视频\n如想看之前更多视频\n添加客服微信进群每天推送更多视频";
                            WeixinUtil.sendCustomMsg(openid, Constants.WEIXIN_MATERIAL_TEXT, txt, mpid);
                            WeixinUtil.sendCustomMsg(openid, Constants.WEIXIN_MATERIAL_IMAGE, redisService.get("kefu_mm"), mpid);
                        }
                        return "";
                    }

                    String result = getClickResponse(eventKey, openid, mpid);
                    if (Strings.isNullOrEmpty(result)) {
                        respMessage = "";
//                        respMessage = "小主，正在生成相关内容，请耐心等待";
//                        return MessageResponse.getTextMessage(fromUserName , toUserName,respMessage);
                    } else if (result.startsWith("media@")) {
                        logger.debug(">>>>>> start to return image message and result = " + result);
                        String[] arr = result.split("@");
                        String mediaId = arr[2];
                        logger.debug(">>>>>> arr[1]=" + arr[1] + " arr[2]=" + arr[2]);
                        if (!Strings.isNullOrEmpty(mediaId))
                            return MessageResponse.getImageMessage(openid, toUserName, mediaId);
                    } else {
                        return MessageResponse.getTextMessage(openid, toUserName, result);
                    }
                } else if (eventType.equals(MessageUtil.EVENT_TYPE_LOCATION)) {// 初次进入的定位事件

                }
            }
            //开启微信声音识别测试 2015-3-30
            else if (msgType.equals(MessageUtil.REQ_MESSAGE_TYPE_VOICE)) {
                String recvMessage = requestMap.get("Recognition").replace("!", "")
                        .replace("！", "").replace("。", "");
                logger.debug("voice is Recognition=======and value is " + recvMessage);

//                if (recvMessage!=null&&Constants.wordMap.containsKey(recvMessage.toUpperCase())){
//                    String word = Constants.wordMap.get(recvMessage.toUpperCase());
//                    logger.error("keyword is meet in the wordMap=======and value is "+word);
//
//                    Article article = serviceUtil.getMatchData(word);
//                    if(article.getUrl()!=null) {
//                        List<Article> list = new ArrayList<Article>();
//                        list.add(article);
//                        return MessageResponse.getNewsMessage(fromUserName , toUserName , list);
//                    }
//                }
//                //respContent = "收到的语音解析结果："+recvMessage;

                if (recvMessage != null) {
                    return processText(openid, toUserName, recvMessage, mpid);
                } else {
                    respContent = "您说的太模糊了，能否重新说清楚点呢";
                }
                return MessageResponse.getTextMessage(openid, toUserName, respContent);
            }
            //照片功能
            else if (msgType.equals(MessageUtil.REQ_MESSAGE_TYPE_IMAGE)) {

                String picUrl = requestMap.get("PicUrl");
                String path = "/fafa/www/img/qnhd/" + requestMap.get("MsgId") + ".jpg";
                logger.debug(">>>path=" + path);

                HttpUtils.downloadFile(picUrl, path);
                String info = matchContextInfo(null, openid);

                if (!Strings.isNullOrEmpty(info) && info.indexOf(Constants.WX_EVT_SCPT) >= 0) {
                    String[] arr = info.split("_");
                    String author = arr.length >= 2 ? arr[1] : null;
                    String fopenid = arr.length >= 3 ? arr[2] : null;
                    String tags = null;
                    if (author.indexOf("@") >= 0) {
                        tags = author.substring(author.indexOf("@") + 1);
                        if (author.indexOf("@") == 0) {
                            author = null;
                        } else {
                            author = author.substring(0, author.indexOf("@"));
                        }
                    }

                    // 取最新空path的english
                    Map qmap = new HashMap<String, Object>();
                    qmap.put("path", 0);
                    qmap.put("orderBy", "id");
                    qmap.put("order", "desc");
                    qmap.put("offset", 0);
                    qmap.put("pageSize", 1);

                    // 更新图片#待完善20190101
//                    EnglishDO english = baikeMapper.selectEnglish(qmap).get(0);
//                    qmap.clear();
//                    qmap = ObjectUtil.objectToMap(english);
                    String imgpath = "/images/english/";
//                    String imgpath = "/images/english/" + english.getPdate() + ".jpg";
//                    qmap.put("path", imgpath);

                    if (author != null) qmap.put("author", author);
                    if (fopenid != null) qmap.put("openid", fopenid);
                    if (tags != null) qmap.put("tags", tags);

                    // 移动拷贝图片
                    // 更新图片#待完善20190101
                    String newPath = "/fafa/www" + imgpath;
//                    FileUtil.copyFile(path, newPath, true);
//                    baikeMapper.updateEnglish(qmap);#待完善20190101
                    try {
                        Runtime.getRuntime().exec("chmod 644 " + newPath);
                    } catch (IOException e) {
                        logger.error("chmod 644 " + newPath + " error", e);
                    }
                    new File(path).delete();

                    // 清空redis
                    String ts = arr[0].substring(5);
//                    redisService.delete(Constants.REDIS_SESSION_TYPE + openid + "_" + ts);
//                    redisService.deleteList(Constants.REDIS_SESSION_TYPE + openid,
//                            Constants.REDIS_EVENT + Constants.WX_EVT_SCPT + "_" + ts);

                    WeixinUtil.sendCustomMsg(openid, Constants.WEIXIN_MATERIAL_TEXT, Constants.OPERATE_OK);
                } else if (!Strings.isNullOrEmpty(info) && info.indexOf(Constants.WX_EVT_SCWXEWM) >= 0) {

                    logger.debug(">>>image WX_EVT_SCWXEWM start");
                    // 上传永久接口
                    JSONObject jo = WeixinUtil.uploadTempMaterial("qianbaidu", path, 0, mpid);
                    redisService.set("wx_qr_" + openid, jo.getString("media_id"));
                    WeixinUtil.delEvtredis(openid, Constants.WX_EVT_SCWXEWM);

                    String reply = "上传二维码成功\n回复：@我的微信二维码\n可查看自己上传的二维码是否正确";
                    WeixinUtil.sendCustomMsg(openid, Constants.WEIXIN_MATERIAL_TEXT, reply);

                    logger.debug(">>>image WX_EVT_SCWXEWM over");

                } else if (!Strings.isNullOrEmpty(info) && info.indexOf(Constants.WX_EVT_SCHBMB) >= 0) {

                    logger.debug(">>>image WX_EVT_SCHBMB start");

                    String hbType = redisService.get(Constants.WX_HAIBAO_TYPE);

                    redisService.set(hbType + "_haibao_template_path", path);
                    WeixinUtil.delEvtredis(openid, Constants.WX_EVT_SCHBMB);

                    String reply = "上传模板成功\n回复：@会过海报\n可查看自己专属的二维码海报";
                    WeixinUtil.sendCustomMsg(openid, Constants.WEIXIN_MATERIAL_TEXT, reply);

                    logger.debug(">>>image WX_EVT_SCHGMB over");
                }
            }
            // 连接
            else if (msgType.equals(MessageUtil.REQ_MESSAGE_TYPE_LINK)) {

            }
            // 地理位置
            else if (msgType.equals(MessageUtil.REQ_MESSAGE_TYPE_LOCATION)) {

            } else {
                return MessageResponse.getTextMessage(openid, toUserName, "返回为空");
            }

        } catch (Exception e) {
            logger.error("weixin processRequest error", e);
        } finally {

        }

        return respMessage;
    }

    /**
     * 处理微信小程序发来的请求
     *
     * @param request
     * @return
     */
    public String processMiniappRequest(HttpServletRequest request, String mpid) {
        String respMessage = "";
        String openid = "";
        // 公众帐号
        String toUserName = "";
        try {
            // 默认返回的文本消息内容
            String respContent = null;

            // xml请求解析
            // 调用消息工具类MessageUtil解析微信发来的xml格式的消息，解析的结果放在HashMap里；
            Map<String, String> requestMap = MessageUtil.parseXml(request);
            logger.debug(">>>>>> requestMap toString:" + JSON.toJSONString(requestMap));

            // 从HashMap中取出消息中的字段；
            // 发送方帐号（open_id）
            openid = requestMap.get("FromUserName");
            // 公众帐号
            toUserName = requestMap.get("ToUserName");
            String createTime = requestMap.get("CreateTime");

            // 消息类型
            String msgType = requestMap.get("MsgType");

            // 消息内容
            String content = requestMap.get("Content");
            // MsgId
            String msgId = requestMap.get("MsgId");

            //图片
            String PicUrl = requestMap.get("PicUrl");


            //进入会话事件
            String Event = requestMap.get("Event");
            String SessionFrom = requestMap.get("SessionFrom");

            // 记录日志
            Map map = new HashMap<String, String>();
            // token
//            String token = WeixinUtil.getAccessToken(mpid);

            if (msgType.equals(MessageUtil.REQ_MESSAGE_TYPE_TEXT)) {
                // 文本消息
                Boolean fasong = getKeywordRes(content, mpid, openid);

                if (!fasong) return MessageResponse.zfkefuMessage(openid, toUserName, createTime);

            } else if (msgType.equals(MessageUtil.REQ_MESSAGE_MINIPROGRAMPAGE)) {
                // 小程序消息
                String AppId = requestMap.get("AppId");
                //PagePath=pages/my/my?tbtype=MerchantApp&fieldname=gzhimg&ywid=11
                String PagePath = requestMap.get("PagePath");
                String ThumbUrl = requestMap.get("ThumbUrl");
                String ThumbMediaId = requestMap.get("ThumbMediaId");
                String Title = requestMap.get("Title");
                String configtype = null;
                String kftext = null;
                String msgtype = Constants.WEIXIN_MATERIAL_IMAGE;

                Map<String, String> pathmap = ObjectUtil.sortQueryMap(PagePath);
                if (pathmap.containsKey("msgtype")) msgtype = pathmap.get("msgtype");

                if (msgtype.equals(Constants.WEIXIN_MATERIAL_IMAGE)) {
                    String mediaid = getPagePathMediaid(pathmap);

                    if (!Strings.isNullOrEmpty(mediaid))
                        WeixinUtil.sendCustomMsg(openid, Constants.WEIXIN_MATERIAL_IMAGE, mediaid);
                    kftext = getPagePathText(pathmap, mpid, configtype);
                    if (!Strings.isNullOrEmpty(mediaid) && !Strings.isNullOrEmpty(kftext))
                        WeixinUtil.sendCustomMsg(openid, Constants.WEIXIN_MATERIAL_TEXT, kftext);

                } else if (msgtype.equals(MessageUtil.REQ_MESSAGE_MINIPROGRAMPAGE)) {

                    String title, pagepath = null;
                    //处理砍价领礼品
                    if (pathmap.containsKey("ywid")) {
                        String ywid = pathmap.get("ywid");
                        String page = pathmap.get("page");
                        configtype = pathmap.get("configtype");

                        String thumb_media_id = getPagePathMediaid(pathmap);
                        if (!Strings.isNullOrEmpty(thumb_media_id) && !Strings.isNullOrEmpty(page)) {
                            Goods goods = goodsService.selectById(ywid);
                            title = page.indexOf("/liping") > 0 ? "请点击下方小程序卡片领取神秘礼物" : goods.getName();
                            pagepath = page + "?gid=" + ywid + "&type=" + goods.getType();
                            WeixinUtil.sendMiniCustomMsg(openid, title, pagepath, thumb_media_id);
                        }

                        if (!Strings.isNullOrEmpty(configtype)) {
                            String[] cfgtypes = configtype.split("-");
                            for (String cfgtype : cfgtypes) {
                                if (cfgtype.split("_").length == 2) {
//                                    回复文字
                                    kftext = getPagePathText(pathmap, mpid, cfgtype);
                                    if (!Strings.isNullOrEmpty(kftext))
                                        WeixinUtil.sendCustomMsg(openid, Constants.WEIXIN_MATERIAL_TEXT, kftext);

                                } else if (cfgtype.split("_").length == 3) {
//                                    回复图片
                                    String summediaid = getMediaidByconfig(cfgtype);
                                    if (!Strings.isNullOrEmpty(summediaid))
                                        WeixinUtil.sendCustomMsg(openid, Constants.WEIXIN_MATERIAL_IMAGE, summediaid);
                                }
                            }
                        }
                    }
                }

//              WeixinUtil.sendCustomMsg(openid, Constants.WEIXIN_MATERIAL_TEXT, Constants.OPERATE_OK);

            } else if (msgType.equals(MessageUtil.REQ_MESSAGE_TYPE_EVENT)) {
                // 事件

            }
            //开启微信声音识别测试 2015-3-30
            else if (msgType.equals(MessageUtil.REQ_MESSAGE_TYPE_VOICE)) {

            }
            //照片功能
            else if (msgType.equals(MessageUtil.REQ_MESSAGE_TYPE_IMAGE)) {

                String picUrl = requestMap.get("PicUrl");
                String path = "/fafa/www/img/qnhd/" + requestMap.get("MsgId") + ".jpg";
                logger.debug(">>>path=" + path);

                HttpUtils.downloadFile(picUrl, path);
                String info = matchContextInfo(null, openid);

                if (!Strings.isNullOrEmpty(info) && info.indexOf(Constants.WX_EVT_SCPT) >= 0) {
                    String[] arr = info.split("_");
                    String author = arr.length >= 2 ? arr[1] : null;
                    String fopenid = arr.length >= 3 ? arr[2] : null;
                    String tags = null;
                    if (author.indexOf("@") >= 0) {
                        tags = author.substring(author.indexOf("@") + 1);
                        if (author.indexOf("@") == 0) {
                            author = null;
                        } else {
                            author = author.substring(0, author.indexOf("@"));
                        }
                    }

                    // 取最新空path的english
                    Map qmap = new HashMap<String, Object>();
                    qmap.put("path", 0);
                    qmap.put("orderBy", "id");
                    qmap.put("order", "desc");
                    qmap.put("offset", 0);
                    qmap.put("pageSize", 1);

                    // 更新图片#待完善20190101
//                    EnglishDO english = baikeMapper.selectEnglish(qmap).get(0);
//                    qmap.clear();
//                    qmap = ObjectUtil.objectToMap(english);
                    String imgpath = "/images/english/";
//                    String imgpath = "/images/english/" + english.getPdate() + ".jpg";
//                    qmap.put("path", imgpath);

                    if (author != null) qmap.put("author", author);
                    if (fopenid != null) qmap.put("openid", fopenid);
                    if (tags != null) qmap.put("tags", tags);

                    // 移动拷贝图片
                    // 更新图片#待完善20190101
                    String newPath = "/fafa/www" + imgpath;
//                    FileUtil.copyFile(path, newPath, true);
//                    baikeMapper.updateEnglish(qmap);#待完善20190101
                    try {
                        Runtime.getRuntime().exec("chmod 644 " + newPath);
                    } catch (IOException e) {
                        logger.error("chmod 644 " + newPath + " error", e);
                    }
                    new File(path).delete();

                    // 清空redis
                    String ts = arr[0].substring(5);
//                    redisService.delete(Constants.REDIS_SESSION_TYPE + openid + "_" + ts);
//                    redisService.deleteList(Constants.REDIS_SESSION_TYPE + openid,
//                            Constants.REDIS_EVENT + Constants.WX_EVT_SCPT + "_" + ts);

                    WeixinUtil.sendCustomMsg(openid, Constants.WEIXIN_MATERIAL_TEXT, Constants.OPERATE_OK);
                } else if (!Strings.isNullOrEmpty(info) && info.indexOf(Constants.WX_EVT_SCWXEWM) >= 0) {

                    logger.debug(">>>image WX_EVT_SCWXEWM start");
                    // 上传永久接口
                    JSONObject jo = WeixinUtil.uploadTempMaterial("qianbaidu", path, 0, mpid);
                    redisService.set("wx_qr_" + openid, jo.getString("media_id"));
                    WeixinUtil.delEvtredis(openid, Constants.WX_EVT_SCWXEWM);

                    String reply = "上传二维码成功\n回复：@我的微信二维码\n可查看自己上传的二维码是否正确";
                    WeixinUtil.sendCustomMsg(openid, Constants.WEIXIN_MATERIAL_TEXT, reply);

                    logger.debug(">>>image WX_EVT_SCWXEWM over");

                } else if (!Strings.isNullOrEmpty(info) && info.indexOf(Constants.WX_EVT_SCHBMB) >= 0) {

                    logger.debug(">>>image WX_EVT_SCHBMB start");

                    String hbType = redisService.get(Constants.WX_HAIBAO_TYPE);

                    redisService.set(hbType + "_haibao_template_path", path);
                    WeixinUtil.delEvtredis(openid, Constants.WX_EVT_SCHBMB);

                    String reply = "上传模板成功\n回复：@会过海报\n可查看自己专属的二维码海报";
                    WeixinUtil.sendCustomMsg(openid, Constants.WEIXIN_MATERIAL_TEXT, reply);

                    logger.debug(">>>image WX_EVT_SCHGMB over");
                }
            }
            // 连接
            else if (msgType.equals(MessageUtil.REQ_MESSAGE_TYPE_LINK)) {

            }
            // 地理位置
            else if (msgType.equals(MessageUtil.REQ_MESSAGE_TYPE_LOCATION)) {

            } else {
                return MessageResponse.getTextMessage(openid, toUserName, "success");
            }

        } catch (Exception e) {
            logger.error("weixin processRequest error", e);
        } finally {

        }
        return null;
    }

    /*
     * 处理文本信息响应处理
     */
    public String processText(String openid, String toUserName, String content, String mpid) {

        String respContent = null;
        logger.debug(">>>>>> start to processText fromUserName=" + openid + ",toUserName=" + toUserName + ",content=" + content);
        logger.debug(">>>>>> Constantsant.Session.Map.get(openid)=" + Constants.SESSION_TYPE_MAP.get(openid));

        if (Strings.isNullOrEmpty(content)) return "";

        // 优先处理回复关键词
        Boolean flag = WeixinUtil.replayKeyWord(content, openid, mpid);
        if (flag) return MessageResponse.getTextMessage(openid, toUserName, "");
        logger.debug("======after replayKeyWord process");

        //微信聊天机器人测试 2015-3-31
//          content = content.replace(" ","");
        Map map = new HashMap<String, String>();
        boolean isExactMatch = true;
        ESResultDO esHewei = new ESResultDO();
        ESResultDO esBaike = new ESResultDO();
        content = content.replace("＋", "+").replace("？", "?");
        Random ran = new Random();

        // 处理添加内容
        respContent = processAddContent(openid, toUserName, content, mpid);
        if (!Strings.isNullOrEmpty(respContent)) {
            logger.debug(">>>processAddContent=" + respContent);
            return MessageResponse.getTextMessage(openid, toUserName, respContent);
        }
        logger.debug(">>> no processAddContent=" + respContent);
        if (content.indexOf("天气") > 0 && RegexUtil.REGEX_AREA.matcher(content).find()) {
//            if(content.indexOf("天气")>0) {

            logger.debug("====WeixinServiceImpl meet to SEARCH_TYPE_WEATHER ");
            // query from rediscache
            content = content.replaceAll(RegexUtil.REGEX_AREA_PREFIX.pattern(), "");
            String city = "";
            Matcher matcher = RegexUtil.REGEX_AREA.matcher(content);
            while (matcher.find()) {
                city = matcher.group(0);
            }
            city += "天气";
            logger.debug("====SEARCH_TYPE_WEATHER city=" + city + " and md5=" + EncryptUtil.md5(city));
            RMap<String, String> rmap = redisService.get(Constants.REDIS_MAP_WEATHER);

            String weather = rmap.get(EncryptUtil.md5(city));

            if (!Strings.isNullOrEmpty(weather)) {
                respContent = weather;
            } else {
                logger.debug("====SEARCH_TYPE_WEATHER start to get Tuling");
                respContent = TulingApiProcess.getTulingResult(city, Constants.SEARCH_TYPE_WEATHER, openid, Constants.HTTP_METHOD_GET);
                rmap.put(EncryptUtil.md5(city), respContent);
            }

        }
//        else if (content.indexOf("笑话") >= 0 || content.indexOf("段子") >= 0) {
//
//            content = content.replaceAll(RegexUtil.REGEX_NOT_JOKE.pattern(), "");
//            if (content.length() > 0) {
//                map.put("content", content);
//                List<JokeDO> list = jokeService.queryJoke(map);
//                respContent = list != null && list.size() > 0 ? list.get(ran.nextInt(list.size())).getContent() : null;
//            }
//            if (Strings.isNullOrEmpty(respContent)) {
//                respContent = jokeService.randomJoke().getContent();
//                if (respContent.indexOf("\\”") > 0) {
//                    respContent = respContent.replace("”", "”\n[太阳]");
//                } else if (respContent.indexOf("。") > 0) {
//                    respContent = respContent.replace("。", "。\n[太阳]");
//                }
//                if (respContent.lastIndexOf("[太阳]") == respContent.length() - 4) {
//                    respContent = "[太阳]" + respContent.substring(0, respContent.length() - 4);
//                }
//            }
//        }
//        else if (content.indexOf("养生") >= 0 && (content.indexOf("格言") >= 0 || content.indexOf("经典") >= 0
//                || content.indexOf("方法") >= 0
//                || content.indexOf("之道") >= 0 || content.indexOf("名言") >= 0) || content.indexOf("名句") >= 0) {
////                content = content.replaceAll(RegexUtil.REGEX_NOT_JOKE.pattern(),"");
////                if(content.length()>0){
////                    map.put("content",content);
////                    List<JokeDO> list = jokeService.queryJoke(map);
////                    respContent = list!=null&&list.size()>0?list.get(0).getContent():null;
////                }
////                if(Strings.isNullOrEmpty(respContent))
//            respContent = mottoService.randomMotto().getContent();
//        }
//        else if ((content.indexOf("运势") >= 0 || content.indexOf("运气") >= 0 || content.indexOf("运程") >= 0)
//                && RegexUtil.REGEX_XINGZUO.matcher(content).find()) {
//            respContent = TulingApiProcess.getTulingResult(content, Constants.SEARCH_TYPE_XINGZUO, openid, Constants.HTTP_METHOD_POST);
//        }
//        else if (content.indexOf("脑筋急转弯") >= 0) {
//
//            respContent = TulingApiProcess.getTulingResult(content, Constants.SEARCH_TYPE_XINGZUO, openid, Constants.HTTP_METHOD_POST);
//        }
//        else if (content.indexOf("故事") >= 0) {
//            respContent = TulingApiProcess.getTulingResult(content, Constants.SEARCH_TYPE_XINGZUO, openid, Constants.HTTP_METHOD_POST);
//        }
//        else if (((content.indexOf("手机号") >= 0 || content.indexOf("姓名") >= 0
//                || content.indexOf("名字") >= 0 || content.indexOf("吉凶") >= 0)
//                && RegexUtil.REGEX_JIXIONG.matcher(content).find())
//                || (Constants.SESSION_TYPE_MAP.get(openid) != null && Constants.SESSION_TYPE_MAP.get(openid) == Constants.SEARCH_TYPE_JIXIONG)) {
//
//            String jixiong = content.replaceAll(RegexUtil.REGEX_JIXIONG.pattern(), "").replaceAll("手机号|姓名|吉凶|的| |_", "");
//            boolean isMobile = false;
//            logger.debug("start to process jixiong=" + jixiong);
//            if (Strings.isNullOrEmpty(jixiong)) {
//
//                respContent = "请回复要查询的手机号或姓名";
//                Constants.SESSION_TYPE_MAP.put(openid, Constants.SEARCH_TYPE_JIXIONG);
//
//            } else if (Constants.SESSION_TYPE_MAP.get(openid) != null
//                    && Constants.SESSION_TYPE_MAP.get(openid) == Constants.SEARCH_TYPE_JIXIONG) {
//                logger.debug("start to process jixiong in SEARCH_TYPE_JIXIONG");
//
//                Matcher xmmacher = RegexUtil.REGEX_XINGMING.matcher(jixiong.replaceAll(RegexUtil.REGEX_NOT_ZHONGWEN.pattern(), ""));
//                Matcher sjmacher = RegexUtil.REGEX_SHOUJIHAO.matcher(jixiong.replaceAll("[^0-9]", ""));
//
//                if (xmmacher.find()) {
//                    jixiong = xmmacher.group() + "这个名字好不好";
//                } else if (sjmacher.find()) {
////                        jixiong = sjmacher.group() + "这个手机号好不好";
//                    jixiong = sjmacher.group();
//                    isMobile = true;
//                } else {
//                    respContent = "请回复正确的手机号或姓名";
//                    if (content.length() == 3 || content.length() == 4 || content.length() == 11) {
//                    } else {
//                        isExactMatch = false;
//                    }
//                }
//                logger.debug("start to process jixiong in SEARCH_TYPE_JIXIONG query" + jixiong);
//
//                if (respContent == null) {
//                    if (isMobile) {
//                        respContent = TulingApiProcess.getHaoling(jixiong);
//                    } else {
//                        respContent = TulingApiProcess.getTulingResult(jixiong, Constants.SEARCH_TYPE_JIXIONG, openid, Constants.HTTP_METHOD_POST);
//                    }
//                    Constants.SESSION_TYPE_MAP.remove(openid, Constants.SEARCH_TYPE_JIXIONG);
//                }
//            } else {
//
//                Matcher xmmacher = RegexUtil.REGEX_XINGMING.matcher(jixiong.replaceAll(RegexUtil.REGEX_NOT_ZHONGWEN.pattern(), ""));
//                Matcher sjmacher = RegexUtil.REGEX_SHOUJIHAO.matcher(jixiong.replaceAll("[^0-9]", ""));
//
//                if (xmmacher.find()) {
//                    jixiong = xmmacher.group() + "这个名字好不好";
//                } else if (sjmacher.find()) {
//                    isMobile = true;
////                        jixiong = sjmacher.group() + "这个手机号好不好";
//                    jixiong = sjmacher.group();
//                }
//
//                logger.debug("start to process jixiong in SEARCH_TYPE_JIXIONG query" + jixiong);
//                if (isMobile) {
//                    respContent = TulingApiProcess.getHaoling(jixiong);
//                } else {
//                    respContent = TulingApiProcess.getTulingResult(jixiong, Constants.SEARCH_TYPE_JIXIONG, openid, Constants.HTTP_METHOD_POST);
//                }
////                  respContent = TulingApiProcess.getTulingResult(jixiong, Constants.SEARCH_TYPE_JIXIONG, openid, Constants.HTTP_METHOD_POST);
//
//                if (Constants.SESSION_TYPE_MAP.get(openid) != null
//                        && Constants.SEARCH_TYPE_JIXIONG == Constants.SESSION_TYPE_MAP.get(openid)) {
//                    Constants.SESSION_TYPE_MAP.remove(openid, Constants.SEARCH_TYPE_JIXIONG);
//                }
//
//            }
//        }
//        else if (content.indexOf("快递") >= 0 ||
//                content.indexOf("订单") >= 0 ||
//                content.indexOf("单号") >= 0 ||
//                (Constants.SESSION_TYPE_MAP.get(openid) != null && Constants.SESSION_TYPE_MAP.get(openid) == Constants.SEARCH_TYPE_EXPRESS)) {
//            String kuaidi = content.replaceAll("查询|快递|单号|编码|编号", "");
//            if (Strings.isNullOrEmpty(kuaidi)) {
//                respContent = "请输入要查询的快递单号";
//                Constants.SESSION_TYPE_MAP.put(openid, Constants.SEARCH_TYPE_EXPRESS);
//            } else {
//                kuaidi = "查询快递" + kuaidi;
//                respContent = TulingApiProcess.getTulingResult(kuaidi, Constants.SEARCH_TYPE_EXPRESS, openid, Constants.HTTP_METHOD_POST);
//                if (Constants.SESSION_TYPE_MAP.get(openid) != null
//                        && Constants.SEARCH_TYPE_EXPRESS == Constants.SESSION_TYPE_MAP.get(openid)) {
//                    Constants.SESSION_TYPE_MAP.remove(openid, Constants.SEARCH_TYPE_EXPRESS);
//                }
//            }
//
//        }
//        else if (content.indexOf("成语接龙") >= 0
//                || (Constants.SESSION_TYPE_MAP.get(openid) != null
//                && Constants.SESSION_TYPE_MAP.get(openid) == Constants.SEARCH_TYPE_CHENGYU)) {
//
//            logger.debug("====WeixinServiceImpl meet to SEARCH_TYPE_CHENGYU  and content =" + content);
//            // query from redis cache
//            if (content.indexOf("成语接龙") >= 0 || content.indexOf("接龙") >= 0) {
//                content = content.replace("成语接龙", "").replace("接龙", "");
//                Constants.SESSION_TYPE_MAP.put(openid, Constants.SEARCH_TYPE_CHENGYU);
//            }
//
//            if (content.indexOf("退出") >= 0 || content.indexOf("推出") >= 0) {
//                Constants.SESSION_TYPE_MAP.remove(openid);
//            } else if (Strings.isNullOrEmpty(content) || content.indexOf("换") >= 0) {
//                String chengyu = chengyuMapper.selectRandomChengyu(ran.nextInt(31851)).getName();
//                respContent = "开始成语接龙，" + chengyu;
//                Constants.SESSION_LAST_WORD_MAP.put(openid + "_" + Constants.SEARCH_TYPE_CHENGYU, chengyu);
//            } else {
//                map.put("name", content);
//
//                List<ChengyuDO> existChengYus = chengyuMapper.selectChengyuList(map);
//
//                if (existChengYus == null || existChengYus.size() == 0) {
//
//                    respContent = "亲，你说的是成语嘛，请重新接龙";
//                    if (content.length() != 4) isExactMatch = false;
//
//                } else {
//                    if (Constants.SESSION_TYPE_MAP.get(openid) == Constants.SEARCH_TYPE_CHENGYU
//                            && !Strings.isNullOrEmpty(Constants.SESSION_LAST_WORD_MAP.get(openid + "_" + Constants.SEARCH_TYPE_CHENGYU))) {
//
//                        String last = Constants.SESSION_LAST_WORD_MAP.get(openid + "_" + Constants.SEARCH_TYPE_CHENGYU);
//                        if (!last.substring(last.length() - 1, last.length()).equals(content.substring(0, 1))) {
//                            respContent = "成语接龙出错，请重新回答";
//                        }
//                    }
//
//                    if (Strings.isNullOrEmpty(respContent)) {
//                        map.put("word", content.substring(content.length() - 1, content.length()));
//                        List<ChengyuDO> chengyus = chengyuMapper.selectFirstLikeChengyu(map);
//                        if (chengyus == null || chengyus.size() == 1) {
//                            respContent = "已接到龙尾，恭喜你打败机器人^*^\n再玩一局，回复：成语接龙XXXX \n不玩了回复：退出";
//                            Constants.SESSION_TYPE_MAP.remove(openid);
//                        } else {
//                            respContent = chengyus.get(ran.nextInt(chengyus.size())).getName();
//                            Constants.SESSION_LAST_WORD_MAP.put(openid + "_" + Constants.SEARCH_TYPE_CHENGYU, respContent);
//                        }
//                    }
//                }
//            }
////              respContent = TulingApiProcess.getTulingResult(content, Constants.SEARCH_TYPE_CHENGYU,openid,Constants.HTTP_METHOD_POST);
//        }
//        else if ((content.indexOf("诗") >= 0 || content.indexOf("词") >= 0)
//                && content.replaceAll(RegexUtil.REGEX_ZHONGWEN.pattern(), "").length() == 0
//                ) {
//            respContent = matchPoem(content, openid);
//        }
//        else if ((content.indexOf("早报") >= 0 ||
//                content.indexOf("简报") >= 0 ||
//                content.indexOf("快报") >= 0 ||
//                content.indexOf("新闻") >= 0 ||
//                content.indexOf("快讯") >= 0 ||
//                content.indexOf("日报") >= 0) && content.length() <= 12) {
//            logger.debug("coming to getDailyMsg....");
//            String query = content.replaceAll(RegexUtil.REGEX_NOT_DAILY.pattern(), "");
//            String result = getDailyMsg(query, null, null);
//            if (Strings.isNullOrEmpty(result)) {
//                result = "暂未采集到快报数据，请稍后再试";
////                    return MessageResponse.getTextMessage(openid , toUserName , result);
//            }
//            // save session context
//            long timestamp = DateUtil.getTime();
//
//            redisService.set(Constants.REDIS_SESSION_TYPE + openid + "_" + timestamp
//                    , query, 2, TimeUnit.DAYS);
//
//            // inputType_matchType_timestamp
//            redisService.setList(Constants.REDIS_SESSION_TYPE + openid,
//                    Constants.REDIS_EVENT + Constants.REDIS_RIBAO + timestamp);
//
//            WeixinUtil.addEvtredis(openid, Constants.REDIS_RIBAO, query, 30, TimeUnit.MINUTES);
//
//            return MessageResponse.getTextMessage(openid, toUserName, result);
//
//        }
//        else if (content.matches(RegexUtil.REGEX_NUM.pattern())) {
//
//            String result = matchContextInfo(content, openid);
//            if (!Strings.isNullOrEmpty(result)) {
////                    Article article = new Article();
////                    article.setTitle("仟仟快报");
////                    article.setDescription(result);
////                    List<Article> articleList = new ArrayList<Article>();
////                    articleList.add(article);
////                    return MessageResponse.getNewsMessage(openid, toUserName, articleList);
//                return MessageResponse.getTextMessage(openid, toUserName, result);
//            }
//        }
//
//        // 进入精确词库查询
//        if (!isExactMatch || Constants.SESSION_TYPE_MAP.get(openid) == null) {
//
//            logger.debug("Constants.wordMap size=" + Constants.wordMap.size() + " content=" + content);
//            if (Constants.wordMap.containsKey(content.toUpperCase())) {
//                String word = Constants.wordMap.get(content.toUpperCase());
//
//                Article article = serviceUtil.getMatchData(word, content.toUpperCase());
//                if (article.getUrl() != null) {
//                    List<Article> list = new ArrayList<Article>();
//                    list.add(article);
//                    return MessageResponse.getNewsMessage(openid, toUserName, list);
//                } else {
//                    respContent = article.getDescription();
//                }
//            }
//        }
//
//        // 非精确模式
//        if (Strings.isNullOrEmpty(respContent) || !isExactMatch) {
//            String keyword = getKeyword(content);
//            logger.debug("====WeixinServiceImpl start to getESHewei search");
//            esHewei = serviceUtil.getMatchField(getESHewei(content));
//            logger.debug("====result from getESHewei =" + JSON.toJSONString(esHewei));
//
//            esBaike = getESBaike(content);
//
//            logger.debug("esHewei.getScore()=" + esHewei.getScore() + "，esBaike.getScore()=" + esBaike.getScore());
//            logger.debug("esHewei.getIssue()=" + esHewei.getIssue() + "，esBaike.getIssue()=" + esBaike.getIssue());
//            logger.debug("esHewei.getAnswer()=" + esHewei.getAnswer() + "，esBaike.getAnswer()=" + esBaike.getAnswer());
//
//            ESResultDO tmp = esHewei.getScore() > esBaike.getScore() ? esHewei : esBaike;
//
//            if (!isExactMatch || Constants.SESSION_TYPE_MAP.get(openid) == null) {
//                respContent = tmp.getAnswer();
//            }
//        }
//
//        // 内部找不到答案，求援外部图灵
//        if (respContent == "" || null == respContent) {
//            respContent = TulingApiProcess.getTulingResult(content, Constants.SEARCH_TYPE_BAIKE, openid, Constants.HTTP_METHOD_GET);
//            if (respContent != null && respContent.length() > 20) {
//                BaikeDO baike = new BaikeDO();
//                baike.setIssue(content);
//                baike.setAnswer(respContent);
//                baike.setDepartId(-1);
//                baike.setRemark("from_tuling");
//                baikeMapper.insertBaike(baike);
//            }
//        }

        if (Strings.isNullOrEmpty(respContent)) respContent = "你问的问题好深奥...";

        //return FormatXmlProcess.formatXmlAnswer(toUserName, openid, respContent);
        return MessageResponse.getTextMessage(openid, toUserName, respContent);

    }

    /**
     * 描述：@param eventKey
     * 描述：@param fromUserName
     * 描述：@param toUserName
     * 描述：@return 接受用户点击事件，通过微信推送给用户消息，跳转页面，发送消息等
     * 作者：herosky
     */
    public String getClickResponse(String eventKey, String openid, String mpid) {
//
//        // TODO 判断evetKey事件处理
//        String mediaId = redisService.get(eventKey + "_" + openid + "_" + DateUtil.getToday());
//
//        if (eventKey.equals("test")) {
//
//        } else if (eventKey.equals("joke")) {
//            String joke = jokeService.randomJoke().getContent();
//            if (joke.indexOf("”") > 0) {
//                joke = joke.replace("”", "”\n[太阳]");
//            } else if (joke.indexOf("。") > 0) {
//                joke = joke.replace("。", "。\n[太阳]");
//            }
//            if (joke.lastIndexOf("[太阳]") == joke.length() - 4) {
//                joke = "[太阳]" + joke.substring(0, joke.length() - 4);
//            }
//            return joke;
//        } else if (eventKey.equals("english")) {
//            if (!Strings.isNullOrEmpty(mediaId)) return "media@mediaId@" + mediaId;
//
//            getEnglishContent(openid, mpid);
//        } else if (eventKey.equals("wisdom")) {
//            if (!Strings.isNullOrEmpty(mediaId)) return "media@mediaId@" + mediaId;
//
//            getWisdomContent(openid, mpid);
//        } else if (eventKey.equals("signin")) {
//            logger.debug(">>>mediaId=" + mediaId);
//            if (!Strings.isNullOrEmpty(mediaId)) return "media@mediaId@" + mediaId;
//
//            logger.debug(">>>after mediaId=" + mediaId);
//            AkkaServer.system.actorOf(Props.create(AKRealTemplate.class)).tell(Constants.WX_EVT_SIGNIN + "@" + openid + "@" + mpid + "@false", ActorRef.noSender());
//        } else if (eventKey.equals("qianbaihui")) {
//            logger.debug(">>>mediaId=" + mediaId);
//            String ranProduct = "hg"+ (new Random().nextInt(16)+1);
//            Boolean flag = WeixinUtil.replayKeyWord(ranProduct,openid);
//            if(flag) return "";
//
//        } else if (eventKey.equals("skill")) {
//            return Constants.EMOJI_CLOVER + "最新推广活动："
//                    + "\n所有关注本公众号的用户均可领5包邮商品"
//                    + "\n\n领取方法："
//                    + "\n点击菜单《仟伯惠》或公众号回复：水果"
////                    + "\n回复商品关键词"
//                    + "\n打开商品图标长按识别小程序码"
//                    + "\n然后下单支付10元购买"
//                    + "\n支付成功后截图给公众号"
//                    + "\n将返你5元红包"
//                    + "\n最终您只花5元购买商品"
//                    + "\n\n（以上以20元商品为例说明，超过20元部分自费）"
//                    + "\n\n注意：每个用户只限购买一次"
//                    + "\n老用户可以联系推广员发放优惠券再次购买";
//
//        } else if (eventKey.equals("du")) {
//            return "";
//        } else if (eventKey.equals("yangsheng")) {
//            return mottoService.randomMotto().getContent();
//        } else if (eventKey.equals("video")) {
//
//            return "video@" + mediaService.randomMedia().getMid();
//        } else if (eventKey.equals("duyixia")) {
//            Random random = new Random();
//            if (random.nextBoolean()) {
//                return mottoService.randomMotto().getContent();
//            } else {
//                return jokeService.randomJoke().getContent();
//            }
//        } else if (eventKey.equals("ribao")) {
//            String ribaoKey = Constants.REDIS_RIBAO_COMMON + DateUtil.getToday();
////            RBucket<String> rbBucket = redis.getBucket(ribaoKey);
//            String ribao = redisService.get(ribaoKey);
//
//            logger.debug(">>>>>> ribao=" + ribao);
//            if (!Strings.isNullOrEmpty(ribao)) {
//                return ribao;
//            } else {
//                ribao = getDailyMsg("", null, null);
//            }
//
//            if (!Strings.isNullOrEmpty(ribao)) {
//                ribao += "\n\n\uD83C\uDF40回复关键词融资新闻，查看近日融资事件";
//                ribao += "\n\uD83C\uDF40回复数字1-12，查看对应快报详情";
//                logger.debug(">>>>>> getDailyMsg ribao=" + ribao);
//                redisService.set(ribaoKey, ribao, 1, TimeUnit.DAYS);
//
//                long timestamp = DateUtil.getTime();
//                redisService.set(Constants.REDIS_SESSION_TYPE + openid + "_" + timestamp,
//                        "", 1, TimeUnit.DAYS);
//
//                // inputType_matchType_timestamp
//                redisService.setList(Constants.REDIS_SESSION_TYPE + openid,
//                        Constants.REDIS_EVENT + Constants.REDIS_RIBAO + timestamp);// 记录事件类型
//
//            } else {
//                ribao = "暂未采集到日报数据，请稍后再试";
//            }
//            return ribao;
//        }
        return null;
    }

    public String wxProcess(String mpid, String actionType, JSONObject json) {

        String accessToken = WeixinUtil.getAccessToken();
        String result = null;

        if (actionType.equals(Constants.WEIXIN_ACT_MENU_CREATE)) {

            String url = Constants.WEIXIN_MENU_CREATE_URL.replace("ACCESS_TOKEN", accessToken);
            result = HttpUtils.httpPost(url, json.toJSONString());
        } else if (actionType.equals(Constants.WEIXIN_ACT_MENU_GET)) {

            String url = Constants.WEIXIN_MENU_GET_URL.replace("ACCESS_TOKEN", accessToken);
            result = HttpUtils.httpGet(url);
            logger.debug(result);
        } else if (actionType.equals(Constants.WEIXIN_ACT_MENU_DELETE)) {

            String url = Constants.WEIXIN_MENU_DELETE_URL.replace("ACCESS_TOKEN", accessToken);
            result = HttpUtils.httpGet(url);
            logger.debug(result);
        }

        return result;
    }

    //
//    private ESResultDO getESBaike(String q) {
//
//        JestClient client = JestUtil.newClient();
//        ESResultDO es = new ESResultDO();
//
//        try {
//            SearchSourceBuilder searchBuilder = new SearchSourceBuilder();
//            searchBuilder.query(QueryBuilders.matchQuery("issue", q));//分词匹配
////            Search s = new Search.Builder(searchBuilder.toString())
////                    .addIndex("i_baike")
////                    .addType("baike")
////                    .build();
//            Search s = new Search.Builder(searchBuilder.toString())
//                    .addIndex("i_baike")
//                    .build();
//
//            SearchResult result = client.execute(s);
//
//            SearchResult.Hit<BaikeDO, Void> hit = result.getFirstHit(BaikeDO.class);
//
//            es.setIssue(hit.source.getIssue());
//            es.setScore(hit.score);
//            es.setAnswer(hit.source.getAnswer());
//            es.setId(hit.source.getId());
//
//            return es;
//
//        } catch (Exception e) {
//            e.printStackTrace();
//        } finally {
//            client.shutdownClient();
//        }
//
//        return es;
//    }
//
//    private ESResultDO getESHewei(String q) {
//
//        JestClient client = JestUtil.newClient();
//        ESResultDO esHewei = new ESResultDO();
//
//        try {
//
//            SearchSourceBuilder searchBuilder = new SearchSourceBuilder();
//            searchBuilder.query(QueryBuilders.matchQuery("question", q));//分词匹配
////            Search s = new Search.Builder(searchBuilder.toString())
////                    .addIndex("i_baike")
////                    .addType("baike")
////                    .build();
//
//            Search s = new Search.Builder(searchBuilder.toString()).addIndex("i_hewei").build();
//            if (RegexUtil.REGEX_PRECRIPTION.matcher(q).find()) {
//                s = new Search.Builder(searchBuilder.toString()).addIndex("i_hewei").addType("prescription").build();
//            } else if (RegexUtil.REGEX_LIQUOR.matcher(q).find()) {
//                s = new Search.Builder(searchBuilder.toString()).addIndex("i_hewei").addType("liquor").build();
//            } else if (RegexUtil.REGEX_GRUEL.matcher(q).find()) {
//                s = new Search.Builder(searchBuilder.toString()).addIndex("i_hewei").addType("gruel").build();
//            }
//
//            logger.debug("=====start to getESHewei =====");
//
//            SearchResult result = client.execute(s);
//
//            SearchResult.Hit<QABean, Void> hit = result.getFirstHit(QABean.class);
//            SearchResult.Hit<QABean, Void> hitSecond = result.getHits(QABean.class).size() > 1 ? result.getHits(QABean.class).get(1) : null;
//            SearchResult.Hit<QABean, Void> hitThird = result.getHits(QABean.class).size() > 2 ? result.getHits(QABean.class).get(2) : null;
//            SearchResult.Hit<QABean, Void> tartgetHit = null;
//
//            logger.debug("=====getESHewei hit.toJSONString = " + JSON.toJSONString(hit));
//            logger.debug("=====getESHewei hitSecond.toJSONString = " + JSON.toJSONString(hitSecond));
//
//            // 相似目标主题短词处理
//            int hitIndex = hit.source.getQuestion() != null && hit.source.getQuestion().replace(",", "，").indexOf("，") > 0 ? hit.source.getQuestion().replace(",", "，").indexOf("，") : hit.source.getQuestion().length();
//            int hitSecondIndex = hit.source.getQuestion() != null && hitSecond.source.getQuestion().replace(",", "，").indexOf("，") > 0 ? hitSecond.source.getQuestion().replace(",", "，").indexOf("，") : hitSecond.source.getQuestion().length();
//
//            String firstWord = hit.source.getQuestion().substring(0, hitIndex);
//            String secondWord = hitSecond.source.getQuestion().substring(0, hitSecondIndex);
//            if (q.indexOf(firstWord) == -1) {
//                tartgetHit = hitSecond;
//            } else {
//                tartgetHit = hit;
//            }
//
//            logger.debug("=====getESHewei result = " + tartgetHit.source.getAnswer());
//
//            esHewei.setIssue(hit.source.getQuestion());
//            esHewei.setScore(hit.score);
//            esHewei.setAnswer(hit.source.getAnswer());
//
//            return esHewei;
//        } catch (Exception e) {
//            logger.error("===== getESHewei error =====", e);
//        } finally {
//            client.shutdownClient();
//        }
//
//        return esHewei;
//    }
//
//    private String matchPoem(String content, String openid) {
//
//        String respContent = null;
//
//        logger.debug("====WeixinServiceImpl meet to matchPoem  and content =" + content);
//        Map<String, String> map = new HashMap<String, String>();
//
//        int mode = 0;
//        if (content.indexOf("首") >= 0) mode = 1;
//        Random ran = new Random();
//        if (content.indexOf("唐诗") >= 0 || content.indexOf("诗") >= 0 ||
//                content.indexOf("诗词") >= 0 || content.indexOf("宋词") >= 0) {
//            String temp = content.replaceAll("来|一首|唐诗|宋词|诗词|诗|首|的|欣赏|鉴赏", "");
//            List<PoemDO> poems = null;
//            PoemDO poem = null;
//            if (!Strings.isNullOrEmpty(temp)) {
//                map.put("searchValue", temp);
//                poems = poemMapper.selectPoemList(map);
//                if (poems.size() > 0) {
//                    String[] yuanwen = poems.get(0).getYuanwen().split("。");
//                    String tmp = yuanwen[ran.nextInt(yuanwen.length - 1)];
//                    logger.debug("====debug poem for yuanwen tmp=" + tmp);
//                    respContent = tmp.substring(0, tmp.indexOf("，"));
//                    return respContent;
//                }
//            } else {
//                poem = poemMapper.selectRandomPoem(ran.nextInt(936));
//                respContent = Strings.isNullOrEmpty(poem.getZhaiyao()) ? poem.getYuanwen() : poem.getZhaiyao();
//                return respContent;
//            }
//        }
//
//        map.put("searchValue", content);
//        List<PoemDO> poems = poemMapper.selectPoemList(map);
//        map.clear();
//        map.put("searchValue", content.replaceAll("来|一首|唐诗|宋词|诗词|诗|首|的|欣赏|鉴赏", ""));
//        List<PoemDO> poems2 = poemMapper.selectPoemList(map);
//        if (poems2 != null && poems2.size() > 0) poems = poems2;
//
//        if (poems.size() > 0) {
//            String[] yuanwen = poems.get(0).getYuanwen().replace("\r", "").replace("\n", "").split("。");
//            boolean isMatch = false;
//            for (String item : yuanwen) {
//
//                logger.debug("====debug poem for yuanwen item=" + item);
//
//                if (isMatch && !Strings.isNullOrEmpty(item)) {
//                    String[] temp = item.split("，");
//                    if (temp.length > 0) {
//                        respContent = temp[0];
//                        break;
//                    }
//                }
//                if (item.indexOf(content) == -1) continue;
//                else {
//                    isMatch = true;
//                    if (item.indexOf(content) == 0) {
//                        item = item.replace(content + "，", "");
//                        String[] temp = item.split("，");
//                        if (temp.length > 0) {
//                            respContent = temp[0];
//                            break;
//                        }
//                    } else {
//                        if (item.indexOf(content) + content.length() < item.length()) {
//                            respContent = item.substring(item.indexOf(content) + content.length() + 1);
//                            break;
//                        }
//                    }
//                }
//            }
//
//            if (isMatch && Strings.isNullOrEmpty(respContent))
//                respContent = "已经是最后一句啦！该诗为" + poems.get(0).getAuthor() + "的名作《" + poems.get(0).getTitle() + "》";
//            else if (Strings.isNullOrEmpty(respContent)) {
//                respContent = poems.get(0).getYuanwen();
//            }
//        }
//
//        return respContent;
//    }
//
//    // 匹配上下文对话信息
    private String matchContextInfo(String query, String openid) {
//        String result = null;
//
//        RList<String> list = redisService.getList(Constants.REDIS_SESSION_TYPE + openid);
//
//        if (list == null || list.size() == 0) {
//            return result;
//        }
//
//        logger.debug(">>>>>>matchContent content=" + list.get(list.size() - 1));
//        // format:inputType_inputInfo_matchType_timestamp
//        // event_ribao_1502862671761
//        String[] arrs = list.get(list.size() - 1).split("_");
//        String inputType = arrs[0];
//        String matchType = arrs[1];
//        String timeStamp = arrs[2];
//        String inputInfo = redisService.get(Constants.REDIS_SESSION_TYPE + openid + "_" + timeStamp);
//
//        Map qmap = new HashMap<String, Object>();
//        qmap.put("openid", openid);
//
//        UserDO user = userMapper.selectUser(qmap);
//        if (openid.equals("")) {
//
//        }
//
//        switch (matchType) {
//            case Constants.WX_EVT_RIBAO:
//                result = Strings.isNullOrEmpty(query) ? "" : getDailyMsg(inputInfo, timeStamp, Integer.valueOf(query));
//                break;
//            case Constants.WX_EVT_SCPT:
//                result = "@scpt" + timeStamp + "_" + inputInfo;
//                if (!Strings.isNullOrEmpty(user.getUnionid()) && !Constants.meList.contains(openid))
//                    result += "_" + user.getUnionid();
//                break;
//            case Constants.WX_EVT_SCWXEWM:
//                result = "@"+Constants.WX_EVT_SCWXEWM + timeStamp + "_" + inputInfo;
//                break;
//            case Constants.WX_EVT_SCHBMB:
//                result = "@"+Constants.WX_EVT_SCHBMB + timeStamp + "_" + inputInfo;
//                break;
//            default:
//                result = null;
//                break;
//        }
//
//        logger.debug(">>>>>>matchContent result=" + result);
//        return result;
        return null;
    }


    /**
     * 添加内容
     *
     * @param openid
     * @param toUserName
     * @param content
     * @return
     */
    private String processAddContent(String openid, String toUserName, String content, String mpid) {

        content = content.replace(":", "：").trim();
        Map map = new HashMap<String, String>();
        String respContent = null;

        if (content.toLowerCase().startsWith("+qz")) {

            String msg = content.substring(3);
            map.put("md5", EncryptUtil.md5(msg));
            map.put("content", msg);
            map.put("note", "");
            map.put("wtype", 3);// 其他为分类
            map.put("origin", "");
            map.put("tag", "");
            map.put("creator", openid);

//    // ==待改进20190101
//            if (wisdomService.queryWisdom(map).size() == 0) {
//                wisdomService.saveWisdom(map);
//            }
            respContent = Constants.OPERATE_OK;
        }
//        else if (content.toLowerCase().startsWith("+xh") || content.startsWith("+笑话")) {
//            String msg = content.substring(3);
//            map.put("md5", EncryptUtil.md5(msg));
//            map.put("content", msg);
//            map.put("title", "");
//            map.put("creator", openid);
//            jokeService.saveJoke(map);
//            respContent = Constants.OPERATE_OK;
//        }
//        else if (content.toLowerCase().startsWith("+ys") || content.startsWith("+养生")) {
//            String msg = content.substring(3).replace(",", "，");
//            map.put("md5", EncryptUtil.md5(msg));
//            map.put("content", msg);
//            map.put("creator", openid);
//            mottoService.saveMotto(map);
//            respContent = Constants.OPERATE_OK;
//
//        }
        else if (content.toLowerCase().startsWith("+jd") || content.startsWith("+经典") ||
                content.toLowerCase().startsWith("+jt") || content.startsWith("+鸡汤") ||
                content.toLowerCase().startsWith("+zs") || content.startsWith("+知识") ||
                content.toLowerCase().startsWith("+zh") || content.startsWith("+智慧")
        ) {
            String msg = content.substring(3).replace(",", "，");

//            this.saveWisdom(msg);//    // ==待改进20190101
            respContent = Constants.OPERATE_OK;
        }
//        else if (content.toLowerCase().startsWith("+qqjs")) {
//            String msg = content.substring(5).replace(",", "，")
//                    .replace(".", "。");
//
//            if (Strings.isNullOrEmpty(msg)) return null;
//            map.clear();
//            String today = DateUtil.getToday();
//            if (msg.lastIndexOf("@") > 0) {
//                today = msg.substring(msg.lastIndexOf("@") + 1);
//                msg = msg.substring(0, msg.lastIndexOf("@"));
//            }
//
//            map.put("tdate", today);
//            TaskDO task = baikeMapper.selectTask(map);
//            if (task != null && task.getId() > 0) {
//                task.setTdate(DateUtil.toDateString(DateUtil.addDay(new Date(), 1), "YYYY-MM-dd"));
//            } else {
//                task = new TaskDO();
//                task.setTdate(today);
//            }
//            task.setContent(msg);
//            baikeMapper.insertTask(task);
//            respContent = Constants.OPERATE_OK;
//        }
//        else if (content.startsWith("+bk") || content.startsWith("+百科")) {
//            String msg = content.substring(3).replace("？", "?")
//                    .replace(",", "，");
//            if (msg.indexOf("?") <= 0) {
//                respContent = "保存百科信息格式不正确！";
//            } else {
//                BaikeDO baike = new BaikeDO();
//                baike.setIssue(msg.substring(0, msg.indexOf("?")));
//                baike.setAnswer(msg.substring(msg.indexOf("?") + 1));
//                baike.setDepartId(0);
//                baikeMapper.insertBaike(baike);
//                respContent = Constants.OPERATE_OK;
//                JestUtil.addESIndex(Integer.valueOf(baike.getId()), "baike", baike);
//            }
//
//        }
//        else if (content.toLowerCase().startsWith("+ll")
//                || content.toLowerCase().startsWith("+dl")
//                || content.toLowerCase().startsWith("+xy")
//                || content.startsWith("+理论")
//                || content.startsWith("+定律")
//                || content.startsWith("+效应")
//                ) {
//            String msg = content.substring(3).replace("？", "?")
//                    .replace(",", "，");
//            if (msg.indexOf("?") <= 0) {
//                respContent = "保存理论信息格式不正确！";
//            }
//            else {
//                BaikeDO baike = new BaikeDO();
//                baike.setIssue(msg.substring(0, msg.indexOf("?")).trim());
//                map.clear();
//                map.put("issue", baike.getIssue());
//                map.put("departId", "250");
//                if (baikeMapper.selectBaike(map).size() == 0) {
//                    logger.debug("start to add new dd|xy|dl");
//                    baike.setAnswer(msg.substring(msg.indexOf("?") + 1));
//                    baike.setDepartId(250);
//                    baikeMapper.insertBaike(baike);
//                    respContent = Constants.OPERATE_OK;
//                    JestUtil.addESIndex(Integer.valueOf(baike.getId()), "baike", baike);
//                } else {
//                    respContent = "已添加该信息！";
//                }
//            }
//        }
//        else if (content.startsWith("+yy") || content.startsWith("+英语")) {
//            String msg = content.substring(3);
//            this.saveEnglish(msg);
//            respContent = Constants.OPERATE_OK;
//        }
        else if (content.startsWith("@pyqpt") || content.startsWith("@朋友圈配图")) {
            String msg = content.substring(6);

            AkkaServer.system.actorOf(Props.create(AKRealTemplate.class)).tell(Constants.WX_CREATE_PYQPT + "@" + openid + "@qnhd@" + msg, ActorRef.noSender());
            respContent = "正在生成图,请耐心等待";

        } else if (content.startsWith("@scpt") || content.startsWith("@上传配图")) {

            WeixinUtil.addEvtredis(openid, Constants.WX_EVT_SCPT, null, 0, null);

            respContent = "请上传你喜欢的配图";

        } else if (content.startsWith("@schbmb") || content.startsWith("@上传海报模板")) {
            logger.debug(">>> @schbmb content=" + content);
            String[] msg = content.substring(8).split("#");
            if (msg.length < 3) {
                return respContent = "⭕上传海报模板指令有误";
            }

            redisService.set(msg[0] + "_haibao_qr_width", msg[1]);
            redisService.set(msg[0] + "_haibao_qr_x", msg[2]);
            redisService.set(msg[0] + "_haibao_qr_y", msg[3]);
            redisService.set(Constants.WX_HAIBAO_TYPE, msg[0]);

            WeixinUtil.addEvtredis(openid, Constants.WX_EVT_SCHBMB, null, 0, null);

            respContent = "请上传会过海报模板";

        } else if (content.startsWith("@scwxewm") || content.startsWith("@上传微信二维码")) {
            String msg = content.substring(8);

            long ts = DateUtil.getTime();
            redisService.set(Constants.REDIS_SESSION_TYPE + openid + "_" + ts,
                    msg, 1, TimeUnit.DAYS);

            redisService.setList(Constants.REDIS_SESSION_TYPE + openid,
                    Constants.REDIS_EVENT + Constants.WX_EVT_SCWXEWM + "_" + ts);

            respContent = "请上传你个人微信二维码";

        } else if (content.startsWith("@pyq") || content.startsWith("@朋友圈")) {
            String msg = content.substring(4);

            AkkaServer.system.actorOf(Props.create(AKRealTemplate.class)).tell(Constants.WX_CREATE_PYQ + "@" + openid + "@" + mpid + "@" + msg, ActorRef.noSender());
            respContent = "正在生成图，请耐心等待";

        } else if (content.startsWith("@qnbpt") || content.startsWith("@仟牛邦配图")) {
            String msg = content.substring(6);

            AkkaServer.system.actorOf(Props.create(AKRealTemplate.class)).tell(Constants.WX_CREATE_QNBPT + "@" + openid + "@" + mpid + "@" + msg, ActorRef.noSender());
            respContent = "正在生成图，请耐心等待";
        } else if (content.startsWith("@qnb") || content.startsWith("@仟牛邦")) {
            String msg = content.substring(4);

            AkkaServer.system.actorOf(Props.create(AKRealTemplate.class)).tell(Constants.WX_CREATE_QNB + "@" + openid + "@" + mpid + "@" + msg, ActorRef.noSender());
            respContent = "正在生成图，请耐心等待";

        } else if (content.startsWith("@wdwxewm") || content.startsWith("@我的微信二维码")) {
            String kval = redisService.get("wx_qr_" + openid);
            WeixinUtil.sendCustomMsg(openid, Constants.WEIXIN_MATERIAL_IMAGE, kval);
            return "打开长按识别二维码，验证是否正确";
        } else if (content.startsWith("@我的") && content.endsWith("推广二维码")) {

            String tpinyin = "";
            String chtxt = content.substring(3, content.indexOf("推广二维码"));
            try {
                tpinyin = Strings.isNullOrEmpty(chtxt) ? "" : PinyinHelper.convertToPinyinString(chtxt, "", PinyinFormat.WITHOUT_TONE);
            } catch (Exception e) {
                logger.error(">>>tpinyin error", e);
            }
            redisService.set(tpinyin, chtxt);
            String path = null;
            String ukey = openid + "__" + tpinyin + "_qr";
            if (redisService.isExists(ukey)) {
                path = redisService.get(ukey);
            } else {
                path = WeixinUtil.getEverShowqrcode(mpid, openid + "__" + tpinyin, 30 * 24 * 60 * 60).get("localpath");
                redisService.set(ukey, path, 30l, TimeUnit.DAYS);
            }
            String mid = WeixinUtil.uploadTempMaterial("image", path, 60, mpid).getString("media_id");

            WeixinUtil.sendCustomMsg(openid, Constants.WEIXIN_MATERIAL_IMAGE, mid);
            return "打开长按识别二维码，验证是否正确\n该二维码有效期为30天\n30天后请重新获取最新最新推广二维码";
        }

        return respContent;
    }

    private String getKeyword(String content) {

        String keyword = content.replaceAll(RegexUtil.REGEX_NOT_KEYWORD.pattern(), "");
        return keyword;
    }
//
//    public void saveDaily(String content) {
//
//        String[] dailys = content.split("\n");
//
//        Map<String, String> map = new HashMap<String, String>();
//        map.put("createTime", DateUtil.getToday());
//        List<DailyDO> exsitDailys = dailyMapper.selectDaily(map);
//        Map<String, Integer> dailysMap = new HashMap<String, Integer>();
//        for (DailyDO item : exsitDailys) {
//            dailysMap.put(item.getMd5(), 1);
//        }
//
//        List<DailyDO> list = new ArrayList<DailyDO>();
//
//        for (String item : dailys) {
//            if (!RegexUtil.REGEX_DAILY.matcher(item).find()
//                    || item.length() > 50) continue;
//
//            String news = item.replaceAll(RegexUtil.REGEX_DAILY.pattern(), "");
//            String md5 = EncryptUtil.md5(news);
//            if (dailysMap.containsKey(md5)) continue;
//
//            DailyDO daily = new DailyDO();
//            daily.setContent(news);
//            daily.setMd5(md5);
//            daily.setType(1);
//            list.add(daily);
//        }
//
//        if (list.size() > 0) {
//            dailyMapper.insertDailyBatch(list);
//            redisService.delete(Constants.REDIS_RIBAO_COMMON + DateUtil.getToday());
//        }
//    }
//
//    public void saveEnglish(String content) {
//
//        String[] dailys = content.split("\n");
//
//        Map<String, String> map = new HashMap<String, String>();
//
//        List<EnglishDO> list = new ArrayList<EnglishDO>();
//
//        for (String item : dailys) {
//            map.clear();
//            String english = item.replaceAll(RegexUtil.REGEX_DAILY.pattern(), "");
//
//            String chinese = null, author = null, tag = null, note = null;
//            int index = english.lastIndexOf("$");
//            if (index > 0) {
//                note = english.substring(index + 1);
//                english = english.substring(0, index);
//            }
//            index = english.lastIndexOf("@");
//            if (index > 0) {
//                tag = english.substring(index + 1);
//                english = english.substring(0, index);
//            }
//            index = english.lastIndexOf("#");
//            if (index > 0) {
//                author = english.substring(index + 1);
//                english = english.substring(0, index);
//            }
//            index = english.lastIndexOf("&");
//            if (index > 0) {
//                chinese = english.substring(index + 1);
//                english = english.substring(0, index);
//            }
//
//            EnglishDO englishDO = new EnglishDO();
//            englishDO.setChinese(chinese);
//            englishDO.setEnglish(english);
//            englishDO.setTags(tag);
//            englishDO.setAuthor(author);
//            englishDO.setNote(note);
//
//            list.add(englishDO);
//        }
//
//        if (list.size() > 0) {
//            baikeMapper.insertPatchEnglish(list);
//        }
//    }

//
//    // ==待改进20190101
//    public void saveWisdom(String content) {
//
//        boolean isGanhuo = content.startsWith("+gh");
//        boolean isZhufu = content.startsWith("+zf");
//        boolean isYingXiaoxue = content.startsWith("+yx");
//        boolean isJingjixue = content.startsWith("+jjx");
//        boolean isXinlixue = content.startsWith("+xlx");
//
//        content = isGanhuo || isYingXiaoxue ||isZhufu? content.substring(3) : content;
//        content = isJingjixue || isXinlixue ? content.substring(4) : content;
//
//        String[] dailys = content.split("\n");
//
//        Map<String, String> map = new HashMap<String, String>();
//        map.put("createTime", DateUtil.getToday());
//
//        List<WisdomDO> list = new ArrayList<WisdomDO>();
//
//        for (String item : dailys) {
//            String news = "";
//            if (RegexUtil.REGEX_DAILY.matcher(item).find()) {
//                news = item.replaceAll(RegexUtil.REGEX_DAILY.pattern(), "");
//            } else {
//                news = item;
//            }
//            if (Strings.isNullOrEmpty(news)) continue;
//            logger.debug("news =" + news);
//
//            String tag = null;
//            String note = null;
//            int index = news.lastIndexOf("###");
//            if (index > 0) {
//                note = news.substring(index + 1);
//                news = news.substring(0, index);
//            }
//            index = news.lastIndexOf("@");
//            if (index > 0) {
//                tag = news.substring(index + 1);
//                news = news.substring(0, index);
//            }
//            news = news.replace("—", "");
//            String origin = null;
//            index = news.lastIndexOf("#");
//            if (index > 0) {
//                origin = news.substring(index + 1);
//                news = news.substring(0, index);
//            }
//            String md5 = EncryptUtil.md5(news);
//            map.clear();
//            map.put("md5", md5);
//            if (wisdomService.queryWisdom(map).size() > 0) continue;
//
//            WisdomDO wisdom = new WisdomDO();
//            wisdom.setContent(news);
//            wisdom.setMd5(md5);
//            wisdom.setTag(tag);
//            wisdom.setNote(note);
//            wisdom.setOrigin(origin);
//            wisdom.setWtype(isGanhuo ? 1 : 0);//1:为干货类 ，在特定上下文有意义  0：鸡汤、智慧、经典
//            if(isZhufu) {
//                wisdom.setWtype(9);//9：祝福
//            }
//            list.add(wisdom);
//        }
//
//        if (list.size() > 0) wisdomService.saveWisdomBatch(list);
//    }

//    private String getDailyMsg(String query, String timeStamp, Integer index) {
//
//        logger.debug("query=" + query + " timeStamp=" + timeStamp + " index=" + index);
//        Map<String, String> map = new HashMap<String, String>();
//        if (timeStamp == null) {
//            map.put("createTime", DateUtil.getToday());
//        } else {
//            map.put("queryTime", DateUtil.toDateString(timeStamp, "yyyy-MM-dd HH:mm:ss"));
//        }
//
//        if (!Strings.isNullOrEmpty(query)) {
//            map.clear();
//            map.put("content", query);
//        }
//        List<DailyDO> list = dailyMapper.selectDaily(map);
//        if (list == null || list.size() == 0) {
//            return null;
//        }
//        if (timeStamp != null) {
//            String tmp = "\uD83C\uDF40" + list.get(index - 1).getContent() + "\n\n\uD83C\uDF40" + list.get(index - 1).getExtra();
//            logger.debug(">>>>>>getDailyMsg match content=" + tmp);
//            return tmp;
//        }
//
//        logger.debug(">>>>>>getDailyMsg not find match content");
//        int m = list.size() >= 12 ? 12 : list.size();
//        StringBuilder sb = new StringBuilder();
//
//        for (int i = 0; i < m; i++) {
//            sb.append((i + 1) + "、" + list.get(i).getContent() + "\n");
//        }
//        return sb.toString();
//
//    }

//
//    // 获取每日英语内容
//    private String getEnglishContent(String openid, String mpid) {
//
//        String filepath = Constants.WX_QBD_IMAGEPATH_ENGLISH + openid + "_" + DateUtil.getToday() + ".png";
//        String englishKey = Constants.REDIS_KEYTYPE_ENGLISH + openid + "_" + DateUtil.getToday();
//        String isEnglishKey = Constants.REDIS_KEYTYPE_IS_ENGLISH + openid + "_" + DateUtil.getToday();
//        String mediaId = "";
//        File file = new File(filepath);
//
//        if (file.exists()) {
//            if (redisService.isnull(isEnglishKey)) {
//                redisService.set(isEnglishKey, "1", 1, TimeUnit.DAYS);
//                mediaId = WeixinUtil.uploadTempMaterial(mpid, Constants.WEIXIN_MATERIAL_IMAGE
//                        , openid, filepath, Constants.WX_EVT_ENGLISH, 1);
//                if (Strings.isNullOrEmpty(mediaId)) {
//                    redisService.set(englishKey, mediaId, 1, TimeUnit.DAYS);
//                    logger.debug(">>>>>> getEnglishContent 1 setRedis englishKey=" + englishKey + " mediaId=" + mediaId);
//                    WeixinUtil.sendCustomMsg(openid, Constants.WEIXIN_MATERIAL_IMAGE, mediaId, mpid);
//                    return mediaId;
//                } else {
//                    logger.debug(">>>>>> getEnglishContent 1 failed");
//                    redisService.delete(isEnglishKey);
//                }
//            }
//        }
//
//        Map map = new HashMap<String, String>();
//        map.put("pdate", DateUtil.getToday());
//
//        List<EnglishDO> list = baikeMapper.selectEnglish(map);
//        EnglishDO english = null;
//        if (list == null || list.size() == 0) {
//            english = baikeMapper.selectLastEnglish(map);
//        } else {
//            english = list.get(0);
//        }
//
//        // 生成新图片
//        String imagefile = "/fafa/www" + english.getPath();
//        logger.debug(">>>>>> english=" + english.getEnglish() + " chinese=" + english.getChinese());
//        List<String> openids = new ArrayList<String>();
//        openids.add(openid);
//        PictureUtil.createEnglishTemplate(imagefile, english.getEnglish(), english.getChinese(), openids, true);
//
//        return mediaId;
//    }

    // 获取仟仟笔记|说词|静说
    private String getWisdomContent(String openid, String mpid) {

        String filepath = Constants.WX_QBD_IMAGEPATH_WISDOM + openid + "_" + DateUtil.getToday() + ".png";
        String wisdomKey = Constants.REDIS_KEYTYPE_WISDOM + openid + "_" + DateUtil.getToday();
        String isWisdomKey = Constants.REDIS_KEYTYPE_IS_WISDOM + openid + "_" + DateUtil.getToday();
        String mediaId = "";
        File file = new File(filepath);

        if (file.exists()) {
            if (redisService.isnull(isWisdomKey)) {

                redisService.set(isWisdomKey, Constants.REDIS_ONE, 1, TimeUnit.DAYS);
                mediaId = WeixinUtil.uploadTempMaterial(mpid, Constants.WEIXIN_MATERIAL_IMAGE
                        , openid, filepath, Constants.WX_EVT_WISDOM, 1);
                redisService.set(wisdomKey, mediaId, 1, TimeUnit.DAYS);
                WeixinUtil.sendCustomMsg(openid, Constants.WEIXIN_MATERIAL_IMAGE, mediaId);
                logger.debug(">>>>>> getWisdomContent setRedis wisdomKey=" + wisdomKey + " mediaId=" + mediaId);
            }
        } else {
            logger.debug(">>>>>> getWisdomContent file not exist " + filepath);
            // true 代表实时生成
            AkkaServer.system.actorOf(Props.create(AKRealTemplate.class))
                    .tell(Constants.WX_EVT_WISDOM + "@" + openid + "@" + mpid + "@true", ActorRef.noSender());

        }

        return "";
    }

    //处理小程序自动回复：图片二维码+文字
    private String getPagePathMediaid(Map<String, String> map) {

        String tbtype = map.get("tbtype");
        String fieldname = map.get("fieldname");
        String ywid = map.get("ywid");

        com.qianniu.napi.admin.entity.Resource res = resourceService.selectOne(new EntityWrapper<com.qianniu.napi.admin.entity.Resource>()
                .eq("tbtype", tbtype).eq("fieldname", fieldname).eq("ywid", ywid).eq("isuse", 1));

        if (tbtype.equals("Store") && fieldname.equals("kefuimg")) {
            Store store = storeService.selectById(ywid);
            if (store.getLeagueid() != null && store.getLeagueid().longValue() > 0) {
                com.qianniu.napi.admin.entity.Resource lmres = resourceService.selectOne(new EntityWrapper<com.qianniu.napi.admin.entity.Resource>()
                        .eq("tbtype", "League").eq("fieldname", "wximg")
                        .eq("ywid", store.getLeagueid()).eq("isuse", 1));
                logger.debug(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>getPagePathMediaid lmres=" + JSON.toJSONString(lmres));
                if (lmres != null && !Strings.isNullOrEmpty(lmres.getMediaid())) return lmres.getMediaid();
            }
        }

        return res == null ? null : res.getMediaid();
    }


    //处理小程序自动回复：图片二维码+文字
    private String getMediaidByconfig(String configtype) {
        if (Strings.isNullOrEmpty(configtype)) return null;
        String[] arr = configtype.split("_");
        String tbtype = arr[0];
        String fieldname = arr[1];
        String ywid = arr[2];

        com.qianniu.napi.admin.entity.Resource res = resourceService.selectOne(new EntityWrapper<com.qianniu.napi.admin.entity.Resource>()
                .eq("tbtype", tbtype).eq("fieldname", fieldname).eq("ywid", ywid).eq("isuse", 1));

        if (tbtype.equals("Store") && fieldname.equals("kefuimg")) {
            Store store = storeService.selectById(ywid);
            if (store.getLeagueid() != null && store.getLeagueid().longValue() > 0) {
                com.qianniu.napi.admin.entity.Resource lmres = resourceService.selectOne(new EntityWrapper<com.qianniu.napi.admin.entity.Resource>()
                        .eq("tbtype", "League").eq("fieldname", "wximg")
                        .eq("ywid", store.getLeagueid()).eq("isuse", 1));
                logger.debug(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>getPagePathMediaid lmres=" + JSON.toJSONString(lmres));
                if (lmres != null && !Strings.isNullOrEmpty(lmres.getMediaid())) return lmres.getMediaid();
            }
        }

        return res == null ? null : res.getMediaid();
    }

    //处理小程序自动回复：图片二维码+文字
    private String getPagePathText(Map<String, String> map, String mpid, String configtype) {

        String tbtype = map.get("tbtype");
        String fieldname = map.get("fieldname");
        String code = tbtype + "_" + fieldname;
        Config config = null;

        if (!Strings.isNullOrEmpty(configtype)) {
            config = configService.selectOne(new EntityWrapper<Config>().eq("code", configtype).eq("mpid", mpid));
        } else {
            config = configService.selectOne(new EntityWrapper<Config>().eq("code", code).eq("mpid", mpid));
        }

        return config == null ? null : config.getRemark();
    }

    //处理小程序自动回复：图片二维码+文字
    private Boolean getKeywordRes(String keywords, String mpid, String openid) {

        Config config = configService.selectOne(new EntityWrapper<Config>()
                .eq("type", "kefukeyword").eq("name", keywords)
                .eq("mpid", mpid));
        if (config == null || Strings.isNullOrEmpty(config.getRestype())) return false;

        if (config.getRestype().equals(MessageUtil.REQ_MESSAGE_TYPE_TEXT)) {
            //文字回复
            if (Strings.isNullOrEmpty(config.getRemark())) return false;

            WeixinUtil.sendCustomMsg(openid, Constants.WEIXIN_MATERIAL_TEXT, config.getRemark());
            return true;
        } else if (config.getRestype().equals(MessageUtil.REQ_MESSAGE_TYPE_IMAGE)) {
            //图片回复
            if (config.getResid() == null) return false;

            com.qianniu.napi.admin.entity.Resource res = resourceService.selectById(config.getResid());
            if (Strings.isNullOrEmpty(res.getMediaid())) return false;

            //发送图片
            WeixinUtil.sendCustomMsg(openid, Constants.WEIXIN_MATERIAL_IMAGE, res.getMediaid());
            //发送文字
            if (!Strings.isNullOrEmpty(config.getRemark()))
                WeixinUtil.sendCustomMsg(openid, Constants.WEIXIN_MATERIAL_TEXT, config.getRemark());

            return true;
        } else if (config.getRestype().equals(MessageUtil.REQ_MESSAGE_MINIPROGRAMPAGE)) {
            //小程序卡片回复

        }

        return false;
    }

    public Map<String, Object> wxappLogin(String code, String guid, Long mpid) {
        try {
            MerchantApp mapp = redisService.getMApp(mpid);

            //通过第一步获得的code获取微信授权信息
            String url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=" + mapp.getAppid() + "&secret="
                    + mapp.getAppsecret() + "&code=" + code + "&grant_type=authorization_code";

            JSONObject jsonObject = AuthUtil.doGetJson(url);
            logger.debug("====================wxappLogin jsonObject" + JSON.toJSONString(jsonObject));

            String openid = jsonObject.getString("openid");
            String access_token = jsonObject.getString("access_token");
            String unionid = jsonObject.getString("unionid");

            String infoUrl = "https://api.weixin.qq.com/sns/userinfo?access_token=" + access_token + "&openid=" + openid
                    + "&lang=zh_CN";

            JSONObject userInfo = AuthUtil.doGetJson(infoUrl);
            logger.debug("====================wxappLogin userInfo" + JSON.toJSONString(userInfo));

            //成功获取授权,以下部分为业务逻辑处理
            if (userInfo != null && !Strings.isNullOrEmpty(openid)) {
                String nickName = userInfo.getString("nickname");
                String avatarUrl = userInfo.getString("headimgurl");
                avatarUrl = avatarUrl.replace("\\", "");

                User user = userService.selectOne(new EntityWrapper<User>().eq("openid", openid));

                HashMap map = new HashMap();

                // 新用户
                map.put("openid", openid);   // openid
                map.put("nickName", nickName); // 昵称
                map.put("avatarUrl", avatarUrl); //头像
                map.put("unionid", unionid); //头像
                map.put("mpid", mpid);
                map.put("mid", ObjectUtil.getMid());
                String ip = ObjectUtil.getIP();
//                  String location = ObjectUtil.getLocation();

                logger.debug("======ip=" + ip);
                map.put("appid", mapp.getAppid());
                map.put("appType", ObjectUtil.getAppType());
                map.put("ip", ip);
                if (!Strings.isNullOrEmpty(guid)) map.put("guid", guid);

                user = updateUser(map);

                //更新成功，返回用户信息
                map.clear();
//              map.put("openid", openid);     // openid
                map.put("nickName", nickName); // 昵称
                map.put("avatarUrl", avatarUrl);  //头像
                map.put("uno", user.getUno());    //用户编号
                map.put("tcode", user.getTcode());    //推荐邀请码

                String key = ObjectUtil.getKey(user);
                String token = AesUtil.encrypt(key, Constants.ENCODE_KEY);
                redisService.set(token, key);
                map.put("token", token);
                logger.debug("======wxappLogin map=" + map);
                return map;
            } else {
                throw new RuntimeException("登录失败!");
            }
        } catch (Exception e) {
            throw new RuntimeException("未知异常!");
        }

    }

    private User updateUser(Map map) {
        logger.debug("--------------------updateUser map=" + map);

        List<User> list = userService.selectList(new EntityWrapper<User>()
                .eq("openid", map.get("openid")).orderBy("mpid", false));

        User user = list == null || list.size() == 0 ? null : list.get(0);
        logger.debug(">>>>>>>>>>>>>>>>>>>>>user openid=" + user);

        if (user == null && map.containsKey("guid"))
            user = userService.selectOne(new EntityWrapper<User>()
                    .eq("guid", map.get("guid")));

        if (user == null) {
            logger.debug(">>>user openid 111");
            user = new User();
            user.setOpenid(map.get("openid").toString());
            user.setNickName(map.get("nickName").toString());
            user.setAvatarPic(map.get("avatarUrl").toString());

//            user.setGender(map.get("gender").toString());
//            user.setCity(map.get("city").toString());
//            user.setProvince(map.get("province").toString());
//            user.setCountry(map.get("country").toString());

            user.setMid(Long.valueOf(map.get("mid").toString()));
            user.setMpid(Long.valueOf(map.get("mpid").toString()));

//            if (map.containsKey("asmpid")) user.setAsmpid(Long.valueOf(map.get("asmpid").toString()));
            user.setApptype(Integer.valueOf(map.get("appType").toString()));

            user.setIsMember(-1);
            user.setHasmp(0);
            user.setState(1);
            user.setIsMch(-1);

            user.setTcode(StringUtil.getGUID().substring(0, 8).toUpperCase());
            while (userService.selectCount(new EntityWrapper<User>().setSqlSelect("id")
                    .eq("mpid", user.getMpid())
                    .eq("tcode", user.getTcode())) > 0) {
                user.setTcode(StringUtil.getGUID().substring(0, 8).toUpperCase());
            }

            user.setGuid(StringUtil.getGUID());

            while (userService.selectCount(new EntityWrapper<User>().setSqlSelect("id").eq("guid", user.getGuid())) > 0) {
                user.setGuid(StringUtil.getGUID());
            }

            User maxuser = userService.selectOne(new EntityWrapper<User>().setSqlSelect("max(uno) uno").eq("mpid", user.getMpid()));
            if (maxuser == null || maxuser.getUno() == null) {
                user.setUno(10000000);
            } else {
                user.setUno(maxuser.getUno() + 1);
            }

            if (map.containsKey("ip"))
                user.setIp(map.get("ip").toString());

            if (map.containsKey("location"))
                user.setLocation(map.get("location").toString());

            user.setCreatetime(new Date());
            user.setMid(ObjectUtil.getMid());

            if (map.containsKey("unionid") && map.get("unionid") != null) {
                user.setUnionid(map.get("unionid").toString());
            }

            MerchantConfig mconfig = redisService.getMconfig(user.getMpid());
            user.setMemberLevel(mconfig.getDefaultMemberLevel());
            user.setUtype(1);
            logger.debug("-------------------------------------------------------------insert user=" + JSON.toJSONString(user));

            //Long puid = ObjectUtil.orderFanuid(oriscene);
            //User puser = puid == null ? null : userService.selectById(puid);
            //String genlink = puser == null ? "0" : (puser.getGenlink() == null ? "0#" + puid : puser.getGenlink() + "#" + puid);
            //user.setGenlink(genlink);

            user.insert();

            logger.debug(">>>user openid 333");
            // 插入默认账户信息
            MerchantConfig mc = redisService.getMconfig(ObjectUtil.getMpid());
            BigDecimal zero = new BigDecimal(0);
            if (mc.getIsMember() == 1) {
                Account act = new Account();
                act.setUid(user.getId());
                act.setNickname(user.getNickName());
                act.setPhone(user.getPhone());
                act.setHeadimg(user.getAvatarPic());

                act.setMid(user.getMid());
                act.setMpid(user.getMpid());
                act.setCreatetime(user.getCreatetime());
                act.setUnionid(user.getUnionid());

                act.setTotal(zero);
                act.setAmount(zero);
                act.setUnuseAmount(zero);
                act.setFanli(zero);
                act.setFanliing(zero);
                act.setFreeze(zero);
                act.setChargeAmount(zero);
                act.setLjxiaofei(zero);
                act.setMamount(zero);
                act.setWithdraw(zero);
                act.insert();
            }

            if (mc.getIsJifen() == 1) {
                Jifen jifen = new Jifen();
                jifen.setState(1);
                jifen.setUid(user.getId());
                jifen.setMid(user.getMid());
                jifen.setMpid(user.getMpid());
                jifen.setCreatetime(user.getCreatetime());
                jifen.setTotal(zero);
                jifen.setFanliing(zero);
                jifen.insert();
            }

            if (user.getMpid() == 12) {
                FanConfig fconfig = redisService.getFanconfig(user.getMpid());
                //注册返积分
                jifenService.addJifenFlow(user.getId(), user.getMid(), user.getMpid(),
                        fconfig.getZhuceMount(), true, FantimeType.now.getVal(),
                        StringUtil.getSnNo(), IotypeEnum.input, JftypeEnum.regist, "", 0l);
            }
            logger.debug(">>>ready to tell akka AKKA_USER_CREATE_AVATOR");
            // 头像,异步创建用户统计信息
            AkkaServer.system.actorOf(Props.create(UserActor.class))
                    .tell(Constants.AKKA_USER_CREATE_AVATOR + "@" + user.getId(), ActorRef.noSender());

        } else {

            user.setOpenid(map.get("openid").toString());
            user.setNickName(map.get("nickName").toString());
            user.setAvatarPic(map.get("avatarUrl").toString());
            user.setModifytime(new Date());
            user.setIp(map.get("ip").toString());

            logger.debug("-------------------------------------------------------------update user=" + JSON.toJSONString(user));

            user.updateById();
        }

        return user;
    }

}
